#include "loginwidget.h"
#include "ui_loginwidget.h"

#include <QMessageBox>

#include "clienthandler.h"

LoginWidget::LoginWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LoginWidget)
{
    ui->setupUi(this);
    ui->cbLogin->setChecked(true);

    QStringList s = SingleTon<LocalUserSql>::getReference().selectUser();
    ui->cbname->addItems(s);

    QObject::connect(ui->btnLogin, &QPushButton::clicked, [=](){
        QString username = ui->cbname->currentText();
       // QString username = ui->leUsenrame->text();
        QString password = ui->lePassword->text();

        if(username.isEmpty() || password.isEmpty()){
            QMessageBox::critical(this, "注册信息", "账号或密码不能为空");
            return;
        }

        ClientHandlerLogin::transfer(username, password);
    });

    QObject::connect(ui->btnRegister, &QPushButton::clicked, [=](){
        QString username = ui->cbname->currentText();
        //QString username = ui->leUsenrame->text();
        QString password = ui->lePassword->text();

        if(username.isEmpty() || password.isEmpty()){
            QMessageBox::critical(this, "注册信息", "账号或密码不能为空");
            return;
        }

        ClientHandlerRegister::transfer(username, password);
    });
}

LoginWidget::~LoginWidget()
{
    delete ui;
}

void LoginWidget::setUsername(QString username)
{
    Username = username;
}

void LoginWidget::insertUser()
{
    QString username = ui->cbname->currentText();
    QString pass = ui->lePassword->text();
    if(ui->cbPassword->isChecked())
    { SingleTon<LocalUserSql>::getReference().insertUser(username,pass);}
    else
    {SingleTon<LocalUserSql>::getReference().insertUser(username,"");}
}

void LoginWidget::on_cbname_currentTextChanged(const QString &arg1)
{
    if(ui->cbLogin->isChecked())
    {
        QString pass = SingleTon<LocalUserSql>::getReference().selectPass(arg1);
        ui->lePassword->setText(pass);
    }

}
